<?php

namespace app\api\service;

use app\api\model\AgentModel;
use app\api\model\ProductCommissionModel;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class ProductCommissionService extends Api
{
    protected static $instance;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 添加、编辑产品佣金
     */
    public function changeProductCommission($params)
    {
        $checkData = [
            'product_id' => 'require',//int(10) DEFAULT NULL COMMENT '产品id',
            'agent_id' => 'require',//int(10) DEFAULT NULL COMMENT '经代公司id',
            'insurance_make_tax' => 'require',//smallint(8) DEFAULT NULL COMMENT '保司补税  百分比',
            'documentary_ratio' => 'require',//smallint(8) DEFAULT NULL COMMENT '跟单比例 百分比',
            'commission_type' => 'require',//tinyint(1) DEFAULT NULL COMMENT '佣金发放方式： 1 固定佣金   2 阶梯佣金',
            'is_co_insurance' => 'require',//tinyint(1) DEFAULT '0' COMMENT '是否多方共保： 0  否    1 是',
        ];
        $checkMsg = [
            'product_id' => '产品标识无效',//int(10) DEFAULT NULL COMMENT '产品id',
            'agent_id' => '经代公司标识无效',//int(10) DEFAULT NULL COMMENT '经代公司id',
            'insurance_make_tax' => '保司补税必填',//smallint(8) DEFAULT NULL COMMENT '保司补税  百分比',
            'documentary_ratio' => '跟单比例必填',//smallint(8) DEFAULT NULL COMMENT '跟单比例 百分比',
            'commission_type' => '佣金结算方式必填',//tinyint(1) DEFAULT NULL COMMENT '佣金发放方式： 1 固定佣金   2 阶梯佣金',
            'is_co_insurance' => '是否多方共保必填',//tinyint(1) DEFAULT '0' COMMENT '是否多方共保： 0  否    1 是',
        ];
        if (isset($params['commission_type']))
        {
            switch ($params['commission_type'])
            {
                case 1:
                    $checkData['promotion_commission'] = 'require';
                    $checkMsg['promotion_commission'] = '固定佣金比例必填';
                    break;
                case 2:
                    $checkData['step_commission'] = 'require';
                    $checkMsg['step_commission'] = '阶梯佣金配置必填';
                    break;
            }
        }
        $Validate = new Validate($checkData, $checkMsg);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        Db::startTrans();
        try{
            ProductCommissionModel::getInstance()->delete([
                'product_id' => ['eq', $params['product_id']]
            ]);
            //经代扣费比例
            $deduction = AgentModel::getInstance()->value([
                'id' => ['eq', $params['agent_id']]
            ], 'deduction');
            $saveData = [
                'product_id' => $params['product_id'],
                'agent_id' => $params['agent_id'],
                'insurance_make_tax' => $params['insurance_make_tax'],
                'documentary_ratio' => $params['documentary_ratio'],
                'net_documentary_ratio' => $params['documentary_ratio'] / (106 - $params['insurance_make_tax']) * (100 - $deduction),
                'commission_type' => $params['commission_type'],
                'promotion_commission' => isset($params['promotion_commission']) ? $params['promotion_commission'] : 0,
                'step_commission' => isset($params['step_commission']) ? json_encode($params['step_commission']) : '',
                'is_co_insurance' => $params['is_co_insurance'],
                'c_time' => datetime(time(), 'Y-m-d H:i:s'),
            ];
            LogService::getInstance()->writeSysLog([
                'operation' => 'api/productCommission/changeProductCommission',
                'title' => '配置产品佣金',
                'content' => $params,
            ]);
            $res = ProductCommissionModel::getInstance()->insert($saveData);
            Db::commit();
            return $res;
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取产品佣金配置信息
     */
    public function getProductCommission($params)
    {
        $Validate = new Validate([
            'product_id' => 'require'
        ], [
            'product_id' => '产品标识无效'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $commission = ProductCommissionModel::getInstance()->find([
            'product_id' => ['eq', $params['product_id']]
        ]);
        $commission['step_commission'] = json_decode($commission['step_commission'], true);
        return $commission;
    }
}